import logging
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from login.forms import RegisterForm, LoginForm
from login.models import User
from utils.jsonoperator import translate2json
from utils.response_code import ResCode, error_map


class LoginView(View):
    def get(self, request):
        return render(request, 'login/index.html')

    def post(self, request):
        try:
            post_data = request.POST
            if not post_data:
                return translate2json(errno=ResCode.PARAMERR, errmsg="参数为空，请输入")
            user_key = ["email", "password", "remember"]
            data_dict = {}
            for key in user_key:
                data_dict[key] = post_data.get(key)
        except Exception as e:
            logging.info("错误信息：\n{}".format(e))
            return translate2json(errno=ResCode.UNKOWNERR, errmsg=error_map[ResCode.UNKOWNERR])
        login_form = LoginForm(data=data_dict, request=request)
        if login_form.is_valid():
            # return render(request, 'home/index.html')  # 需要重定向
            return redirect(reverse('apiwork:index'))
        else:
            err_msg_list = []
            for item in login_form.errors.get_json_data().values():
                err_msg_list.append(item[0].get('message'))
            err_msg_str = '/'.join(err_msg_list)
            return translate2json(errno=ResCode.PARAMERR, errmsg=err_msg_str)


class ForgotView(View):
    def get(self, request):
        return render(request, 'login/forgot.html')


class RegisterView(View):
    def get(self, request):
        return render(request, 'login/register.html')

    def post(self, request):
        user_register_form = RegisterForm(data=request.POST)
        if user_register_form.is_valid():
            username = user_register_form.cleaned_data.get('username')
            password = user_register_form.cleaned_data.get('password')
            email = user_register_form.cleaned_data.get('email')
            if not request.POST.get('aggree'):
                return translate2json(errno=ResCode.AGGREE, errmsg=error_map[ResCode.AGGREE])
            new_user = User.objects.create(username=username, password=password, email=email)
            new_user.save()
            # return render(request, 'login/index.html') # 错误写法，导致注册后页面跳转但url没有重定向
            return redirect('login:login')
        else:
            return HttpResponse("注册输入有误，请重新输入~")


class ResetView(View):
    def get(self, request):
        return render(request, 'login/reset.html')
